<?php

namespace App\Http\Controllers;

use App\Model\Category;
use App\Model\Users;
use App\Models\Live\Anchor;
use App\Models\Live\LiveCategory;
use App\Models\Tag\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Predis\Client;

class AnchorController extends Controller
{
    const NEED_POINT = 100;
    const CATE_LIMIT = 20;

    public function follow(Request $request,Anchor $anchor)
    {
        $user = session('user');

        if (!$user) {
            return ['error' => '2', 'msg' => '请先登录。'];
        }

        if ($anchor->followers()->where('user_id', $user->id)->first()) {
            return $this->_unfollow($user, $anchor);
        } else {
            return $this->_follow($user, $anchor);
        }
    }

    public function index(Request $request)
    {
        $p_cate = Category::where('cate_name', '直播')->first();
        $cates = Category::where('cate_pid', $p_cate->cate_id)->orderBy('cate_weight','asc')->get();
        $liveTop = $this->getLiveTop($cates);
        $cates = $cates->map(function ($cate) {
            $cate->count = $this->getCateCount($cate);
            return [
                'cate' => $cate,
                'items' => $this->getCateAnchors($cate, 11),
            ];
        });
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")) {
            return view('mobile.anchor.anchor_list')
                ->with('p_cate',$p_cate)
                ->with('cates', $cates)
                ;
        }else{
            return view('home.anchor.new-index')
                ->with('p_cate',$p_cate)
                ->with('cates', $cates)
                ->with('rec_top', $liveTop)
                ->with('top', $liveTop)
                ;
        }
    }

    public function cate(Request $request, Category $cate)
    {

        $p_cate = Category::where('cate_name', '直播')->first();
        $cates = Category::where('cate_pid', $p_cate->cate_id)->orderBy('cate_weight','asc')->get();

        $page = $request->has('page') ? (int)$request->input('page') : 1;

        $page = $page > 0 ? $page : 1;

        if ($page > 3) return ['msg' => "更多主播试试搜索哦！"];
        $anchors = $this->getCateAnchors($cate, self::CATE_LIMIT, $page);

        $agent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")) {
            return $request->ajax() ? $anchors : view('mobile.anchor.anchor_cate_list')
                ->with('cates', $cates)
                ->with('anchors', $anchors)
                ->with('cate_info', $cate)
                ;
        }else{

            return $request->ajax() ? $anchors : view('home.anchor.cate')
                ->with('cates', $cates)
                ->with('anchors', $anchors)
                ->with('cate_info', $cate)
                ;
        }

    }

    /**
     * @param Category $cate
     * @param int $limit
     * @param int $page
     * @return \Illuminate\Support\Collection
     */
    public function getCateAnchors($cate, $limit, $page = 1)
    {
        if (empty($cate)) return collect();

        $start = ($page - 1) * $limit;
        $end = $start + $limit - 1;

        $anchors = \Redis::zrevrange('zLives.'.$cate->cate_id, $start, $end);
        $anchors = \Redis::hmget('hLives', $anchors);
        return collect($anchors)->map(function ($an) {
            return new Anchor((array)json_decode($an));
        });

//        return Cache::remember("lives.cate.{$cate->cate_id}.{$limit}.{$page}", 5, function ()
//        use ($cate, $limit, $page){
//            $anchors = Anchor::join('tags', 'tags.anchor_id', '=', 'anchors.id')
//                ->ofCate($cate->cate_id)
//                ->where('anchors.status', 1)
//                ->where('tags.is_rec', 1)
//                ->orderBy('anchors.online', 'desc')
//                ->skip(($page - 1) * self::CATE_LIMIT)
//                ->take($limit)
//                ->get()
//            ;
//
//            return $anchors->merge(
//                Anchor::ofCate($cate->cate_id)
//                    ->where('status', 1)
//                    ->whereNotIn('id', $anchors->pluck('anchor_id')->all())
//                    ->orderBy('online', 'desc')
//                    ->skip(($page - 1) * self::CATE_LIMIT)
//                    ->take($limit - $anchors->count())
//                    ->get()
//            );
//        });
    }

    public function getCateCount($cate)
    {
        return \Redis::zcard('zLives.'.$cate->cate_id);
//        return Cache::remember("lives.count.{$cate->cate_id}", 5, function () use($cate) {
//            return Anchor::ofCate($cate->cate_id)
//                ->where('status', 1)
//                ->count();
//        });
    }

    public function getRecTop($limit = 5)
    {
        return collect([]);Anchor::join('tags', 'tags.anchor_id', '=', 'anchors.id')
            ->where('anchors.status', 1)
            ->where('tags.is_rec', 1)
            ->orderBy('anchors.online', 'desc')
            ->take($limit)
            ->get();
    }

    public function getLiveTop($cates)
    {
        return collect($cates)->map(function ($cate) {
            $live_id = \Redis::zrevrange('zLives.'.$cate->cate_id, 0, 1);
            return isset($live_id[0]) ? new Anchor((array)json_decode(\Redis::hget('hLives', $live_id[0]))) : false;
        })
            ->filter(function ($t) {return $t;})
            ->sortByDesc('online')
            ->take(5);
//        return collect([1,2,3,4,6])
//            ->map(function ($live_id) {
//                return Anchor::where('live_id', $live_id)->where("status", 1)->orderBy('online', 'desc')->first();
//            })
//            ->sortBy('online')
//            ;
    }

    private function _follow($user, $anchor)
    {
        $user = Users::find($user->id);

        if ($user->points < self::NEED_POINT) return ['error' => '2', 'msg' => '积分不足。'];

        $user->points -= self::NEED_POINT;

        $user->save();
        session('user', $user);

        $anchor->followers()->attach($user->id);

        return ['error' => '1', 'msg' => '关注成功。'];
    }

    private function _unfollow($user, $anchor)
    {
        $anchor->followers()->detach($user->id);
        return ['error' => '1', 'msg' => '取消关注成功。'];
    }

    public function search(Request $request)
    {
        $query = Anchor::select('anchors.name', 'lives.name as live_name', 'anchors.url', 'anchors.cover', 'anchors.avatar')
            ->orderBy('online', 'desc')
            ->join('lives', 'lives.id', '=', 'anchors.live_id')
        ;

        if ($request->has('s')) {
            $query->where(function ($query) use($request) {
                foreach (explode(' ', $request->input('s')) as $search) {
                    $query->orWhere('anchors.name', 'like', "%{$search}%");
                }
                return $query;
            });
        }

        if ($request->has('live')) {
            $query->where('live_id', $request->input('live'));
        }

        return ($query->paginate(20));
    }

    public function show($tag)
    {
        if ($tag instanceof  Tag) {
            $anchor = new Anchor((array)json_decode(\Redis::hget('hLives', $tag->anchor_id)));
            $anchor->status = 1;
        } else {
            return redirect()->route('anchor.preview', [$tag]);
        }
        $user = session('user');
        
        if (!empty($user)) $user = Users::find($user->id);

        $rec_anchors = $this->getCateAnchors($anchor->cate, 16);
        $p_cate = Category::where('cate_name', '直播')->first();
        $cates = Category::where('cate_pid', $p_cate->cate_id)->orderBy('cate_weight','asc')->get();


        $agent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")) {
            return view('mobile.anchor.anchor_detail')
                ->with('anchor', $anchor)
                ->with('tag', $tag)
                ->with('rec_anchors', $rec_anchors)
                ->with('cates', $cates)
                ->with('user', $user)
                ;
        }else{
            if ($tag->is_rec) {
                return view('home.anchor.rec-show')
                    ->with('anchor', $anchor)
                    ->with('tag', $tag)
                    ->with('rec_anchors', $rec_anchors)
                    ->with('cates', $cates)
                    ->with('user', $user)
                    ->with('top', $this->getRecTop(4))
                    ;
            } else{
                return view('home.anchor.show')
                    ->with('anchor', $anchor)
                    ->with('tag', $tag)
                    ->with('rec_anchors', $rec_anchors)
                    ->with('cates', $cates)
                    ->with('user', $user)
                    ;
            }
        }

    }

    public function preview($anchor_id)
    {
        if ($tag = Tag::where('anchor_id', $anchor_id)->first()) {
            return redirect('/anchors/'.$tag->id);
        }
        $anchor = new Anchor((array)json_decode(\Redis::hget('hLives', $anchor_id)));
        $user = session('user');

        if (!empty($user)) $user = Users::find($user->id);

        $rec_anchors = $this->getCateAnchors($anchor->cate, 4);
        $p_cate = Category::where('cate_name', '直播')->first();
        $cates = Category::where('cate_pid', $p_cate->cate_id)->orderBy('cate_weight','asc')->get();



        $agent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")) {
            return view('mobile.anchor.anchor_detail')
                ->with('anchor', $anchor)
                ->with('tag', Tag::find(Tag::min('id')))
                ->with('rec_anchors', $rec_anchors)
                ->with('cates', $cates)
                ->with('user', $user)
                ;
        }else{
            return view('home.anchor.show')
                ->with('anchor', $anchor)
                ->with('tag', Tag::find(Tag::min('id')))
                ->with('rec_anchors', $rec_anchors)
                ->with('cates', $cates)
                ->with('user', $user)
                ;
        }

    }
}
